import permision from './permission.js'
import store from '@/store/index.js'

export async function getLocation(cb) {
	// #ifdef APP-PLUS
	let status = await checkPermission();
	if (status !== 1) {
		return status;
	}
	// #endif
	
	if (typeof cb == 'function') cb && typeof cb == 'function' && cb(status)
	// doGetLocation();
}

/**
 * 获取当前位置信息
 */
export const doGetLocation = () => {
	uni.getLocation({
		success: (res) => {
            // 根据个人所需处理
			// store.commit('SET_LOCATION', {
			// 	lng: res.longitude,
			// 	lat: res.latitude
			// });
			console.log('当前位置：', res.longitude, res.latitude);
		},
		fail: (err) => {
			if (err.errMsg.indexOf("auth deny") >= 0) {
				uni.showToast({
					title: "访问位置被拒绝",
					icon: 'none'
				})
			} else {
				uni.showToast({
					title: err.errMsg,
					icon: 'none'
				})
			}
		}
	})
}

/**
 * 检测定位权限
 */
async function checkPermission() {
	let status = permision.isIOS ? await permision.requestIOS('location') :
		await permision.requestAndroid('android.permission.ACCESS_FINE_LOCATION');

	if (status === null || status === 1) {
		status = 1;
	} else if (status === 2) {
		uni.showModal({
			content: "系统定位已关闭",
			showCancel: false,
			success: function(res) {}
		})
	} else if (status.code) {
		uni.showModal({
			content: status.message
		})
	} else {
		uni.showModal({
			content: "为了您更好的体验App蓝牙功能，需要获取位置信息，请点击设置开启定位权限",
			confirmText: "设置",
			success: function(res) {
				if (res.confirm) {
					permision.gotoAppSetting();
				}
			}
		})
	}

	return status;
}


const location = {
	getLocation
}
export default location;
